package org.hang.jvm;

import org.hang.jvm.classfile.ClassFile;
import org.hang.jvm.classpath.Classpath;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

/**
 * 参数 -Xjre "~/.jdks/adopt-openjdk-1.8.0_292/jre" java.lang.Object
 */
public class App {
    private static final Logger log = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) {
        Cmd cmd = Cmd.parse(args);
        if (!cmd.isOk() || cmd.isHelpFlag()) {
            log.info("Usage: <main class> [-options] class [args...");
            return;
        }
        if (cmd.isVersionFlag()) {
            log.info("java version \"1.8.0\"");
            return;
        }
        startJvm(cmd);
    }

    private static void startJvm(Cmd cmd) {
        String args = Optional.ofNullable(cmd.getArgs()).map(list -> String.join(",", list)).orElse(null);
        Classpath cp = new Classpath(cmd.getJre(), cmd.getClasspath());
        log.info("\nclasspath: {}\nclass: {}\nargs: {}\n", cp, cmd.getManClass(), args);
        // 获取className
        String className = cmd.getManClass().replace(".", "/");
        ClassFile classFile = loadClass(className, cp);
        assert classFile != null;
        printClassInfo(classFile);
    }

    private static void printClassInfo(ClassFile classFile) {

    }

    private static ClassFile loadClass(String className, Classpath classpath) {
        try {
            byte[] classData = classpath.readClass(className);
            return new ClassFile(classData);
        } catch (Exception e) {
            log.error("Could not find or load main class " + className);
            return null;
        }
    }

}
